package Tree;

import java.util.ArrayList;
import java.util.LinkedList;

public class p剑指Offer32从上到下打印二叉树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    class Solution {
        public int[] levelOrder(TreeNode root) {
            if (root == null) return new int[0];
            ArrayList<Integer> list = new ArrayList<>();
            LinkedList<TreeNode> nodes = new LinkedList<>();
            nodes.add(root);
            while(!nodes.isEmpty()){
                int size = nodes.size();
                for(int i = 0; i < size; i++){
                    TreeNode node = nodes.removeFirst();
                    list.add(node.val);
                    if (node.left != null) nodes.add(node.left);
                    if (node.right != null) nodes.add(node.right);
                }
            }
            return list.stream().mapToInt(i -> i).toArray();
        }
    }
}
